<?php
/**
 * User: lv
 * Date: 2019/5/30 12:35
 * Email: 578530370@qq.com
 */

namespace app\index\controller;

use app\common\controller\CommonController;
use app\common\model\AuthModel;
use app\common\model\WxUserInfoModel;
use app\common\model\Code;

class RegisterController extends CommonController
{
    public function login()
    {
        $mobile = input('mobile');
        $code = input('code');
        $data = [
            'mobile' => $mobile,
            'code' => $code,
        ];

        //数据验证
        $result = $this->validate($data, 'app\common\validate\MoblieValidate.login');
        if (true !== $result) {
            return $this->errJson($result);
        }

        $codeInfo = Code::where('mobile', $mobile)->find();
        if(!empty($codeInfo)){
            //判断验证码
            if($codeInfo['code'] == $code) {
                $infoAuth = AuthModel::where('mobile', $mobile)->field('uid,status,token')->find();
                //判断是否注册
                $token = $this->setToken();
                if (empty($infoAuth)) {
                    $createAuth = [
                        'mobile'    => $mobile,
                        'token'     => $token,
                        'ctime'     => time(),
                        'status'    => 1,
                        'utime'     => time()
                    ];
                    if (AuthModel::create($createAuth)) return $this->okJson('ok', ['token' => $token, 'status' => 1]);
                } else {
                    $updateAuth = [
                        'token' => $token,
                        'utime' => time(),
                    ];
                    if (AuthModel::update($updateAuth, ['uid' => $infoAuth['uid']])) {
                        return $this->okJson('ok', ['token' => $token, 'status' => $infoAuth['status']]);
                    }
                }
            }else {
                return $this->errJson('验证码错误');
            }
        }else {
            return $this->errJson('验证码错误');
        }
    }

    public function getUserInfo()
    {
        $code = input('code');
        $token = input('token');
        if(empty($code) || empty($token)) return $this->errJson('缺少参数');

        $info = AuthModel::where('token', $token)->field('uid,status,token')->find();
        if(empty($info)){
            return $this->errJson('token失效');
        }elseif($info['status'] >= 2){
            return $this->errJson('微信已认证');
        }else{
            $uid = $info['uid'];
        }

        $appid = config('wechat.appId');
        $appsecret = config('wechat.secret');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
        $res = json_decode(file_get_contents($url),true);

        if (isset($res['errcode']) && $res['errcode']) {
            $this->redirect('getCode');
        }
        $access_token = $res["access_token"];
        $openid = $res["openid"];

        $urls = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $userInfo = json_decode(file_get_contents($urls), true);

        if($info['status'] == 1){
            $userData = [
                'uid' => $uid,
                'nickName' => $userInfo['nickname'],
                'gender' => $userInfo['sex'],
                'city' => $userInfo['city'],
                'province' => $userInfo['province'],
                'country'=> $userInfo['country'],
                'avatarUrl' => $userInfo['headimgurl'],
                'ctime' => time(),
            ];
            if(WxUserInfoModel::create($userData)) {
                AuthModel::update(['status' => 2, 'utime' => time()], ['uid' => $uid]);
                return $this->okJson('成功',['token'=>$info['token'], 'status'=>2]);
            }
        }else{
            return $this->okJson('成功',['token'=>$info['token'], 'allow'=>$info['status']]);
        }
    }

    public function getCode()
    {
        $appid = config('wechat.appId');
        $redirect_uri = urlencode("http://gxsh.tktjh.com/");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        header("location:".$url);
    }
}